﻿package ywh.stream
{
	import ywh.event.SyncEvent;
	import ywh.manager.Core;
	import ywh.manager.CoreState;
	import ywh.manager.Sync;
	import ywh.player.PlayerState;
	
	/**
	 * 主要流
	 * @author 杨伟华
	 */
	public class MainStream extends MediaStream
	{
		private static var _$:MainStream;
		private static var _streamTime:Number;
		private static var _streamState:String;
		
		public function MainStream(p:PrivateClass)
		{
			if (!p || _$)
			{
				throw(new Error("MainStream是一个单例类，请调用MainStream.$"));
			}
			else
			{
				_$ = this;
			}
		}
		
		static public function get $():MainStream
		{
			return _$ || new MainStream(new PrivateClass());
		}
		
		static public function clear$():void
		{
			_$ = null;
		}
		
		override protected function handlePreSync(e:SyncEvent):void
		{
			if (!_streamIsReady || !shower)
			{
				Core.state = CoreState.CORE_UNINITIALIZED;
				Sync.preventSyncOnce();
			}
			else
			{
				shower.preSyncHandle();
				var tempCalcTime:Number = currentItem.startTime + (isNaN(shower.time) ? 0:shower.time);
				if (_streamTime == tempCalcTime)
				{
					switch (shower.state)
					{
						case PlayerState.ENDED: 
							nextAvilable ? nextItem() : (Core.state = CoreState.CORE_END);
							break;
						case PlayerState.PAUSED: 
							Core.state = CoreState.CORE_PAUSED;
							break;
						case PlayerState.PLAYBACK_ERROR: 
							Core.state = CoreState.CORE_ERROR;
							break;
						default: 
							Core.state = CoreState.CORE_BUFFERING;
							break;
					}
					Sync.preventSyncOnce();
				}
				else
				{
					_streamTime = tempCalcTime;
					Core.state = CoreState.CORE_PLAYING;
				}
			}
		}
		
		/**
		 * 主流播放
		 */
		public function play():void
		{
			shower && shower.play();
		}
		
		/**
		 * 主流暂停
		 */
		public function pause():void
		{
			shower && shower.pause();
		}
		
		/**
		 * 主流获取或者设置课程时间;
		 */
		public function get time():Number
		{
			return _streamTime;
		}
		
		public function set time(value:Number):void
		{
			var index:uint = _list.getIndexByStartTime(value);
			canChangeIndexTo(index) && changeItemTo(index);
			shower.seekTo(value - currentItem.startTime);
		}
		
		/**
		 * 主流持续时间;
		 */
		public function get duration():Number
		{
			return _list.totalDuration;
		}
	
	}

}

class PrivateClass
{
}